package com.power.web.user;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.Cookie;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.power.Constants;
import com.power.model.member.TmMember;
import com.power.model.user.TsSysuser;
import com.power.services.hospital.HospitalService;
import com.power.services.member.TmMemberService;
import com.power.services.user.SysuserService;
import com.power.util.BASE64Util;
import com.power.util.StringUtil;
import com.power.web.action.base.AbstractBaseAction;

public class SysuserAction extends AbstractBaseAction {
    
    /**
     * 
     */
    private static final long serialVersionUID = -2221699813751703241L;
    
    @Autowired
    @Qualifier("sysuserService")
    private SysuserService sysuserService;
    
    @Autowired
    @Qualifier("tmMemberService")
    private TmMemberService tmMemberService;
    
    @Autowired
    @Qualifier("hospitalService")
    private HospitalService hospitalService;
    
    private String loginFailure;
    
    private String user;
    
    private String pass;
    
    private TsSysuser tsSysuser;
    
    private TmMember tmMember;
    
    /**
     * 用户登录
     * 
     * @return
     */
    @SuppressWarnings("unchecked")
    public String loginNoJSON() {
        String result = "loginFailure";
        this.loginFailure = "错误的用户名密码！";
        this.session.put(Constants.LOGIN_FAILURE, this.loginFailure);
        List<TsSysuser> lst = this.sysuserService.findByLogonnameWithDate("1",this.user);
        if (lst.size() > 0) {
            TsSysuser user = (TsSysuser)lst.get(0);
            if (StringUtil.compareString(BASE64Util.getBASE64(this.pass), user.getPassword())) {
                if ("1".equals(user.getCategory())) {
                    this.session.put(Constants.USERINFO_KEY, user);
                    this.session.remove(Constants.LOGIN_FAILURE);
                    this.loginFailure = "";
                    result = "loginSuccess";
                }
            }
        }
        return result;
    }
    
    public String logout() {
        this.loginFailure = "";
        this.session.remove(Constants.LOGIN_FAILURE);
        this.session.remove(Constants.ONLINE_USER_LISTENER_NAME);
        this.session.remove(Constants.USERINFO_KEY);
        return "loginFailure";
    }
    
    @SuppressWarnings("unchecked")
    public String changePassword() {
        String json = "{failure:true,msg:'修改密码失败！'}";
        TsSysuser userInfo = (TsSysuser)this.session.get(Constants.USERINFO_KEY);
        TsSysuser user = (TsSysuser)this.sysuserService.read(userInfo.getId());
        user.setPassword((this.pass));
        try {
            this.sysuserService.updatePassword(user);
            json = "{success:true, msg:'密码修改成功！'}";
            userInfo.setPassword((this.pass));
            this.session.put(Constants.USERINFO_KEY, userInfo);
            this.response.reset();
            this.response.setCharacterEncoding("UTF-8");
            this.response.getWriter().print(json);
        }
        catch (Exception e) {
            log.error("密码修改错误！", e);
        }
        
        return null;
    }
    
    public String exit() {
        try {
            request.getSession().invalidate();
        }
        catch (Exception e) {
            log.error("退出错误", e);
        }
        return "exit";
    }
    
    public String qiantanExit() {
        try {
            request.getSession().invalidate();
        }
        catch (Exception e) {
            log.error("退出错误", e);
        }
        return "home";
    }
    
    /**
     * web前台登陆
     * 
     * @return 0 代表失败 1代表成功 2代码 账号还被锁住
     */
    public String forwordLogin() {
        
        try {
            String json = "{result:0}";
            List<TsSysuser> list = sysuserService.findByLogonnameAndPassword(tsSysuser);
            if (list != null && list.size() > 0) {
                TsSysuser tsUser = list.get(0);
                if ("2".equals(tsUser.getLock())) {
                    json = "{result:2}";
                }
                else {
                    Cookie userNameCookie = new Cookie("username", tsUser.getUsername());
                    Cookie passwordCookie = new Cookie("password", tsUser.getPassword());
                    response.addCookie(userNameCookie);
                    response.addCookie(passwordCookie);
                    json = "{result:1}";
                }
            }
            this.response.setCharacterEncoding("UTF-8");
            this.response.getWriter().print(json);
        }
        catch (Exception e) {
            log.error("用户登入失败！", e);
        }
        return null;
    }
    
    /**
     * web前台登陆 form表单提交
     * 
     * @return 0 代表失败 1代表成功 2代码 账号还被锁住
     */
    public String forwordLogin1() {
        List lstUser = null;
        TsSysuser user;
        String result = "webloginFailure";
        this.loginFailure = "错误的用户名密码！";
        if ((this.user == null) || (this.pass == null)) {
            try {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print("<script>alert('错误的用户名密码！');</script>");
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        try {
            lstUser = this.sysuserService.findByLogonnameWithDate("2",this.user.trim());
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        
        if ((lstUser != null) && (lstUser.size() > 0)) {
            user = (TsSysuser)lstUser.get(0);
            if (StringUtil.compareString(BASE64Util.getBASE64(this.pass), user.getPassword())) {
                if (!"2".equals(user.getCategory())) {
                    try {
                        response.setContentType("text/html;charset=utf-8");
                        response.getWriter().print("<script>alert('错误的用户名密码！');</script>");
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                    // return result;
                }
                if ("2".equals(user.getLock())) {
                    try {
                        response.setContentType("text/html;charset=utf-8");
                        response.getWriter().print("<script>alert('您的账号还未激活，无法登入，请登录邮箱激活后再试！');</script>");
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                    // return result;
                }
                tmMember = tmMemberService.findTmMemberById(user.getId().toString());
                tmMember.setProviceName(hospitalService.getProName(tmMember.getDistrictId()));
                tmMember.setDistrictName(hospitalService.getDistrictName(tmMember.getDistrictId()));
                user.setMemberid(tmMember.getTemId());
                user.setDistrictId(tmMember.getDistrictId());
                user.setRealName(tmMember.getRealName());
                user.setDistrictName(tmMember.getDistrictName());
                user.setEmail(tmMember.getEmail());
                user.setIdcard(tmMember.getIdcard());
                user.setPhone(tmMember.getPhone());
                user.setProviceName(tmMember.getProviceName());
                user.setDistrictName(tmMember.getDistrictName());
                user.setSex(tmMember.getSex());
                user.setProviceId(tmMember.getProviceId());
                this.session.put("tmMember", tmMember);
                this.session.put(Constants.USERINFO_KEY, user);
                this.session.remove(Constants.LOGIN_FAILURE);
                this.loginFailure = "";
                result = "webloginSuccess";
                try {
                    response.setContentType("text/html;charset=utf-8");
                    String path = request.getContextPath();
                    String basePath =
                        request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
                            + "/";
                    response.getWriter().print("<script>parent.window.location.href='" + basePath
                        + "member/showMemInfo.action';</script>");
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
        }
        this.session.put(Constants.LOGIN_FAILURE, this.loginFailure);
        try {
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().print("<script>alert('错误的用户名密码！');</script>");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public String memberInfo() {
        try {
            TsSysuser userInfo = (TsSysuser)this.session.get(Constants.USERINFO_KEY);
            tmMember = tmMemberService.findTmMemberById(userInfo.getId().toString());
            tmMember.setProviceName(hospitalService.getProName(tmMember.getDistrictId()));
            tmMember.setDistrictName(hospitalService.getDistrictName(tmMember.getDistrictId()));
        }
        catch (Exception e) {
        }
        return "webloginSuccess";
    }
    
    public String findPassword() {
        return null;
    }
    
    public String getUser() {
        return user;
    }
    
    public void setUser(String user) {
        this.user = user;
    }
    
    public String getPass() {
        return pass;
    }
    
    public void setPass(String pass) {
        this.pass = pass;
    }
    
    public TsSysuser getTsSysuser() {
        return tsSysuser;
    }
    
    public void setTsSysuser(TsSysuser tsSysuser) {
        this.tsSysuser = tsSysuser;
    }
    
    public TmMember getTmMember() {
        return tmMember;
    }
    
    public void setTmMember(TmMember tmMember) {
        this.tmMember = tmMember;
    }
}
